package control;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import dao.DAOFactory;
import dao.Entidad;

import bean.Producto;

/**
 * Servlet implementation class Servlet
 */
@WebServlet("/ServletProducto")
public class ServletProducto extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletProducto() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		if(request.getParameter("action")!=null){
			String action=(String)request.getParameter("action");
			List<Producto> listProducto= new ArrayList<Producto>();
			Gson gson = new Gson();
			response.setContentType("application/json");
			DAOFactory factory=DAOFactory.getFactoryConcrete(DAOFactory.MYSQL);
			Entidad<Producto> productodao= factory.getProductoDAO();
			
			if(action.equals("list")){
				try{
					
					listProducto = productodao.listAll();					
					
					JsonElement element = gson.toJsonTree(listProducto,new TypeToken<List<Producto>>(){}.getType());
					JsonArray jsonArray = element.getAsJsonArray();
					String listData=jsonArray.toString();
					
					listData="{\"Result\":\"OK\",\"Records\":"+listData+"}";					
					
					response.setHeader("Cache-control", "no-cache, no-store");
			        response.setHeader("Pragma", "no-cache");
			        response.setHeader("Expires", "-1");
					response.getWriter().print(listData);
					System.out.println(listData);
					
				}catch(Exception ex){
					String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace()+"}";
					response.getWriter().print(error);
					System.out.println(error);
				}
				
			}else if(action.equals("create") || action.equals("update")){
			    Producto producto=new Producto();
			    
			    try{
			    	
			    if(request.getParameter("id_prod")!=null){       
				       int productoid=Integer.parseInt(request.getParameter("id_prod"));
				       producto.setId_prod(productoid);
				       System.out.println("IDDDD : " +productoid );
			    }
			    if(request.getParameter("nomb_prod")!=null){
				       String nombre=(String)request.getParameter("nomb_prod");
				       producto.setNomb_prod(nombre);
			    }
			    if(request.getParameter("desc_prod")!=null){
				       String descripcion=(String)request.getParameter("desc_prod");
				       producto.setDesc_prod(descripcion);
			    }
			    if(request.getParameter("gara")!=null){
				       Double garantia=Double.parseDouble((String)request.getParameter("gara"));
				       producto.setGara(garantia);
			    }
			    if(request.getParameter("stoc")!=null){
				       int stock=Integer.parseInt((String)request.getParameter("stoc"));
				       producto.setStoc(stock);
				}
			    if(request.getParameter("prec")!=null){
				       Double precio=Double.parseDouble((String)request.getParameter("prec"));
				       producto.setPrec(precio);
				}
			    if(request.getParameter("id_marc")!=null){
				       int id_marca=Integer.parseInt((String)request.getParameter("id_marc"));
				       producto.setId_marc(id_marca);
				}
			    if(request.getParameter("mode_prod")!=null){
			    		String modelo = (String)request.getParameter("mode_prod");
			    		producto.setMode_prod(modelo);
			    }
			    
			    }catch(Exception e){
			    	System.out.print("Error al capturar datos " + e.getMessage());
			    }
			    
			    try{           
			     if(action.equals("create")){//Create new record
			      productodao.insert(producto);     
			      listProducto.add(producto);
			      //Convert Java Object to Json    
			      String json=gson.toJson(producto);     
			      //Return Json in the format required by jTable plugin
			      String listData="{\"Result\":\"OK\",\"Record\":"+json+"}";           
			      response.getWriter().print(listData);
			     }else if(action.equals("update")){//Update existing record
			      productodao.update(producto);
			      String listData="{\"Result\":\"OK\"}";         
			      response.getWriter().print(listData);	  
			     }
			    }catch(Exception ex){
			      String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace().toString()+"}";
			      response.getWriter().print(error);
			    }
			   }else if(action.equals("delete")){//Delete record
			    try{
			     if(request.getParameter("id_prod")!=null){
			     Producto producto=new Producto();
			     	try{
			     		if(request.getParameter("id_prod")!=null){       
			     		int productoid=Integer.parseInt(request.getParameter("id_prod"));
						producto.setId_prod(productoid);
						}
					}catch(Exception e){
					    System.out.print("Error al capturar datos " + e.getMessage());
					}
			      productodao.delete(producto);
			      String listData="{\"Result\":\"OK\"}";        
			      response.getWriter().print(listData);
			     }
			    }catch(Exception ex){
			    String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace().toString()+"}";
			    response.getWriter().print(error);
			   }    
			  }

			
			
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		doGet(request, response);
	}

}
